import axios from 'axios';

const state = {
  user: null,
  loading: false
}

const mutations = {
  SET_USER (state, user) {
    state.user = user;
  },
  LOGIN_PENDING (state) {
    state.loading = true;
  },
  LOGIN_SUCCESS (state) {
    state.loading = false;
  }
}

const actions = {
  login ({ commit }, loginForm) {
    let data = new FormData();
    data.append('username', loginForm.username);
    data.append('password', loginForm.password);
    return axios.post('/login', data).then((response) => {
        console.log(response.data);
        commit('SET_USER', response.data.body);
        commit('LOGIN_SUCCESS');
    });
  },
  logout ({ commit }) {
    return new Promise((resolve) => {
      axios.post('/logout').then((response) => {
        console.log('注销' + response.status);
      });
      commit('SET_USER', null);
      resolve();
    });
  }
}

const getters = {
  user: state => state.user,
  loading: state => state.loading
}

const loginModule = {
  state,
  mutations,
  actions,
  getters
}

export default loginModule;